package sbox

import (
	"gitee.com/dennis-kk/service-box-go/util/config/source/apollo"
	"gitee.com/dennis-kk/service-box-go/util/errors"
	"gitee.com/dennis-kk/service-box-go/util/tools"
)

const (
	boxLogo = `
 ______  __       ______   ______  ______   ______   ______   __  __    
/\  == \/\ \     /\  __ \ /\__  _\/\  __ \ /\  == \ /\  __ \ /\_\_\_\   
\ \  _-/\ \ \____\ \  __ \\/_/\ \/\ \ \/\ \\ \  __< \ \ \/\ \\/_/\_\/_  
 \ \_\   \ \_____\\ \_\ \_\  \ \_\ \ \_____\\ \_____\\ \_____\ /\_\/\_\ 
  \/_/    \/_____/ \/_/\/_/   \/_/  \/_____/ \/_____/ \/_____/ \/_/\/_/
`
)

type (
	Option func(*Options)

	ServiceCfg struct {
		//CustomName service nickname cache
		CustomName map[uint64]string `yaml:"custom_name"`
	}

	HostInfo struct {
		InnerHost  string `yaml:"host"`
		PublicHost string `yaml:"expose_host"`
	}

	Options struct {
		index     int
		cfgPath   string
		proxyMode bool
		args      []string
		host      []HostInfo
		option    string         // user custom option
		apolloCfg *apollo.Config // apollo config
		logo      string         // application logo
	}
)

func NewBoxOptions() *Options {
	return &Options{
		logo:      boxLogo,
		apolloCfg: apollo.NewConfig(),
	}
}

func (o *Options) PreHosts() error {
	if len(o.host) < 1 {
		return errors.HostIpError
	}

	for idx := range o.host {
		if addr, err := tools.ParseIp(o.host[idx].InnerHost); err != nil {
			return err
		} else {
			o.host[idx].InnerHost = addr
		}

		if addr, err := tools.ParseIp(o.host[idx].PublicHost); err != nil {
			return err
		} else {
			o.host[idx].PublicHost = addr
		}
	}
	return nil
}

func (o *Options) GetOneHostIp() string {
	if len(o.host) == 0 {
		panic("no valid public host info")
	}

	o.index = (o.index + 1) % len(o.host)
	if len(o.host[o.index].PublicHost) == 0 {
		return o.host[o.index].InnerHost
	} else {
		return o.host[o.index].PublicHost
	}
}

func WithOsArgs(args []string) Option {
	return func(o *Options) {
		o.args = args
	}
}
